package com.zll.study;

/**
 * 
 */
public class NC100将字符串转化为整数 {
    public int atoi (String str) {
        // write code here
        if (str.isEmpty()){
            return 0;
        }
        str = str.replaceAll(" ", "");    //去掉所有空格
        //System.out.println("str:" + str);
        char first = '0';
        char last = '9';
        int count = 0;
        int negative = 0;   //判断有无负号
        int positive = 0;   //判断有无正数
        int[] ans = new int[100];
        double val = 0;
        for (int i = 0; i < str.length(); i++){
            char temp = str.charAt(i);
            if (temp >= first && temp <= last){
                ans[count] = temp - '0';
                count++;
            }else if (count == 0 && (temp == '+' || temp == '-')){
                if (temp == '+'){
                    positive = 1;
                }else if (temp == '-'){
                    negative = 1;
                }
            }else{
                break;
            }
        }
        //System.out.println("count:" + count);
        for (int i = 0; i < count; i++){
            double tmp = 1;
            for (int j = count - 1 - i; j > 0; j--){
                tmp = tmp * 10;
            }
            val = ans[i] * tmp + val;
        }
        if (negative == 1){
            val = -val;
        }
        if (val >= Integer.MAX_VALUE){
            //System.out.println("chn");
            return Integer.MAX_VALUE;
        }
        if (val <= Integer.MIN_VALUE ){
            return Integer.MIN_VALUE;
        }
        return (int)val;
    }

}
